<template>
  <div class="patrol-task-add-container">
    <el-card class="box-card">
      <div slot="header" class="card-header">
        <span class="header-title"><i class="el-icon-plus header-icon"></i> 添加巡更任务</span>
      </div>
      <el-form :model="taskForm" :rules="rules" ref="taskForm" label-width="120px" class="animated-form">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="所属社区" prop="communityId" class="fade-in-item">
              <el-select 
                v-model="taskForm.communityId" 
                placeholder="请选择社区" 
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="item in communityOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="巡更计划" prop="planId" class="fade-in-item">
              <el-select 
                v-model="taskForm.planId" 
                placeholder="请选择巡更计划" 
                style="width: 100%"
                @change="handlePlanChange"
                filterable
                :disabled="!taskForm.communityId"
              >
                <el-option
                  v-for="item in planOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">
          <span class="divider-content"><i class="el-icon-time"></i> 任务时间设置</span>
        </el-divider>

        <el-form-item label="任务类型" prop="taskType" class="fade-in-item">
          <el-radio-group v-model="taskForm.taskType" @change="handleTaskTypeChange" class="custom-radio-group">
            <el-radio :label="0">
              <div class="radio-content">
                <i class="el-icon-date"></i> 单次任务
                <div class="radio-description">创建一次性执行的巡更任务</div>
              </div>
            </el-radio>
            <el-radio :label="1">
              <div class="radio-content">
                <i class="el-icon-refresh"></i> 定时任务
                <div class="radio-description">创建按计划重复执行的巡更任务</div>
              </div>
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <transition name="fade">
          <div v-if="taskForm.taskType === 0" class="task-config-section">
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="执行日期" prop="taskDate" class="fade-in-item">
                  <el-date-picker
                    v-model="taskForm.taskDate"
                    type="date"
                    placeholder="请选择执行日期"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    style="width: 100%"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="计划时间" prop="plannedTime" class="fade-in-item">
              <div class="time-picker-container">
                <el-time-picker
                  v-model="taskForm.plannedStartTime"
                  placeholder="开始时间"
                  format="HH:mm:ss"
                  value-format="HH:mm:ss"
                  class="time-picker"
                ></el-time-picker>
                <div class="time-separator">
                  -
                </div>
                <el-time-picker
                  v-model="taskForm.plannedEndTime"
                  placeholder="结束时间"
                  format="HH:mm:ss"
                  value-format="HH:mm:ss"
                  class="time-picker"
                ></el-time-picker>
              </div>
            </el-form-item>
          </div>
        </transition>

        <transition name="fade">
          <div v-if="taskForm.taskType === 1" class="task-config-section">
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="有效日期" prop="validDateRange" class="fade-in-item">
                  <el-date-picker
                    v-model="taskForm.validDateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    style="width: 100%"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="重复方式" prop="repeatType" class="fade-in-item">
              <el-radio-group v-model="taskForm.repeatType" class="repeat-type-group">
                <el-radio :label="1">
                  <div class="repeat-type-item">
                    <i class="el-icon-date"></i> 每天
                  </div>
                </el-radio>
                <el-radio :label="2">
                  <div class="repeat-type-item">
                    <i class="el-icon-date"></i> 每周
                  </div>
                </el-radio>
                <el-radio :label="3">
                  <div class="repeat-type-item">
                    <i class="el-icon-date"></i> 每月
                  </div>
                </el-radio>
              </el-radio-group>
            </el-form-item>

            <transition name="fade">
              <el-form-item v-if="taskForm.repeatType === 2" label="重复日期" prop="weekDays" class="fade-in-item">
                <div class="week-days-container">
                  <el-checkbox-group v-model="taskForm.weekDays">
                    <el-checkbox :label="1" class="day-checkbox">周一</el-checkbox>
                    <el-checkbox :label="2" class="day-checkbox">周二</el-checkbox>
                    <el-checkbox :label="3" class="day-checkbox">周三</el-checkbox>
                    <el-checkbox :label="4" class="day-checkbox">周四</el-checkbox>
                    <el-checkbox :label="5" class="day-checkbox">周五</el-checkbox>
                    <el-checkbox :label="6" class="day-checkbox">周六</el-checkbox>
                    <el-checkbox :label="0" class="day-checkbox">周日</el-checkbox>
                  </el-checkbox-group>
                </div>
              </el-form-item>
            </transition>

            <transition name="fade">
              <el-form-item v-if="taskForm.repeatType === 3" label="重复日期" prop="monthDays" class="fade-in-item">
                <div class="month-days-container">
                  <el-checkbox-group v-model="taskForm.monthDays">
                    <el-checkbox v-for="day in 31" :key="day" :label="day" class="month-day-checkbox">{{ day }}日</el-checkbox>
                  </el-checkbox-group>
                </div>
              </el-form-item>
            </transition>

            <el-form-item label="计划时间" prop="plannedTime" class="fade-in-item">
              <div class="time-picker-container">
                <el-time-picker
                  v-model="taskForm.plannedStartTime"
                  placeholder="开始时间"
                  format="HH:mm:ss"
                  value-format="HH:mm:ss"
                  class="time-picker"
                ></el-time-picker>
                <div class="time-separator">
                  -
                </div>
                <el-time-picker
                  v-model="taskForm.plannedEndTime"
                  placeholder="结束时间"
                  format="HH:mm:ss"
                  value-format="HH:mm:ss"
                  class="time-picker"
                ></el-time-picker>
              </div>
            </el-form-item>
          </div>
        </transition>

        <el-divider content-position="left">
          <span class="divider-content"><i class="el-icon-location"></i> 巡更点位设置</span>
        </el-divider>

        <el-form-item label="巡更点位" class="fade-in-item">
          <div class="point-list">
            <div class="table-toolbar">
              <span class="point-count">
                <i class="el-icon-map-location"></i> 共 {{ pointList.length }} 个巡更点
              </span>
            </div>
            <el-table 
              :data="pointList" 
              border 
              style="width: 100%" 
              :header-cell-style="{background:'#f5f7fa'}"
              v-loading="loading"
              empty-text="请先选择巡更计划"
              stripe
              highlight-current-row
              class="custom-table"
            >
              <el-table-column label="序号" width="60" align="center">
                <template slot-scope="scope">
                  {{ scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column prop="name" label="巡更点名称" width="150" align="center"></el-table-column>
              <el-table-column prop="code" label="位置编号" width="120" align="center"></el-table-column>
              <el-table-column prop="location" label="位置" width="150" align="center"></el-table-column>
              <el-table-column prop="category" label="巡更类别" width="120" align="center"></el-table-column>
            </el-table>
          </div>
        </el-form-item>

        <el-form-item class="form-buttons fade-in-item">
          <el-button 
            type="primary" 
            :loading="submitting" 
            @click="submitForm" 
            icon="el-icon-check"
            class="submit-button"
          >提交</el-button>
          <el-button @click="cancel" icon="el-icon-back">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 表单数据
      taskForm: {
        communityId: null,
        planId: null,
        taskDate: null,
        plannedStartTime: null,
        plannedEndTime: null,
        taskType: 0, // 0-单次任务, 1-定时任务
        repeatType: 1, // 1-每天, 2-每周, 3-每月
        weekDays: [], // 周重复的日期 [0-6]
        monthDays: [], // 月重复的日期 [1-31]
        validDateRange: [] // 有效期范围 [startDate, endDate]
      },
      // 表单验证规则
      rules: {
        communityId: [
          { required: true, message: '请选择社区', trigger: 'change' }
        ],
        planId: [
          { required: true, message: '请选择巡更计划', trigger: 'change' }
        ],
        taskDate: [
          { required: true, message: '请选择执行日期', trigger: 'change' }
        ],
        validDateRange: [
          { required: true, type: 'array', message: '请选择有效日期范围', trigger: 'change' }
        ],
        weekDays: [
          { type: 'array', required: true, message: '请至少选择一天', trigger: 'change' }
        ],
        monthDays: [
          { type: 'array', required: true, message: '请至少选择一天', trigger: 'change' }
        ],
        plannedStartTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        plannedEndTime: [
          { required: true, message: '请选择结束时间', trigger: 'change' }
        ]
      },
      // 社区选项
      communityOptions: [],
      // 巡更计划选项
      planOptions: [],
      // 巡更点位列表
      pointList: [],
      // 加载状态
      loading: false,
      // 提交状态
      submitting: false
    };
  },

  created() {
    // 初始加载数据
    this.loadCommunityOptions();
  },

  methods: {
    // 加载社区选项
    loadCommunityOptions() {
      this.loading = true;
      this.$axios
        .get("api/infrastructure-server/community/queryAll")
        .then(response => {
          if (response.data && response.data.code === 200) {
            this.communityOptions = response.data.data.map(item => {
              return { value: item.id, label: item.name };
            });
          } else {
            this.$message.error(response.data.message || "获取社区列表失败");
          }
        })
        .catch(error => {
          console.error("获取社区列表错误:", error);
          this.$message.error("获取社区列表错误");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 根据社区加载巡更计划选项
    loadPlanOptions(communityId) {
      this.loading = true;
      this.$axios
        .get(`api/patrol-server/patrolPlan/queryByCommunityId/${communityId}`)
        .then(response => {
          if (response.data && response.data.code === 200) {
            this.planOptions = response.data.data.map(item => {
              return { value: item.planId, label: item.planName };
            });
          } else {
            this.$message.error(response.data.message || "获取巡更计划列表失败");
          }
        })
        .catch(error => {
          console.error("获取巡更计划列表错误:", error);
          this.$message.error("获取巡更计划列表错误");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 社区选择变更
    handleCommunityChange(val) {
      this.taskForm.planId = null;
      this.pointList = [];
      if (val) {
        this.loadPlanOptions(val);
      } else {
        this.planOptions = [];
      }
    },

    // 巡更计划选择变更
    handlePlanChange(val) {
      if (val) {
        this.loadPlanPoints(val);
      } else {
        this.pointList = [];
      }
    },

    // 任务类型变更
    handleTaskTypeChange(val) {
      if (val === 0) {
        // 单次任务，清空定时任务相关字段
        this.taskForm.repeatType = 1;
        this.taskForm.weekDays = [];
        this.taskForm.monthDays = [];
        this.taskForm.validDateRange = [];
      } else {
        // 定时任务，清空单次任务相关字段
        this.taskForm.taskDate = null;
      }
    },

    // 加载巡更计划点位
    loadPlanPoints(planId) {
      this.loading = true;
      this.$axios
        .get(`api/patrol-server/patrolTask/queryPointByPlanId/${planId}`)
        .then(response => {
          if (response.data && response.data.code === 200) {
            this.pointList = response.data.data.map(item => {
              return {
                id: item.pointId,
                name: item.pointName,
                code: item.locationCode,
                location: item.buildingName,
                category: item.categoryName
              };
            });
          } else {
            this.$message.error(response.data.message || "获取巡更点位列表失败");
          }
        })
        .catch(error => {
          console.error("获取巡更点位列表错误:", error);
          this.$message.error("获取巡更点位列表错误");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 提交表单
    submitForm() {
      this.$refs.taskForm.validate(valid => {
        if (valid) {
          // 构建提交数据
          let taskData = {
            communityId: this.taskForm.communityId,
            planId: this.taskForm.planId,
            plannedStartTime: this.taskForm.plannedStartTime,
            plannedEndTime: this.taskForm.plannedEndTime,
            taskType: this.taskForm.taskType,
            pointList: this.pointList.map(point => {
              return {
                pointId: point.id
              };
            })
          };

          // 根据任务类型添加不同字段
          if (this.taskForm.taskType === 0) {
            // 单次任务
            taskData.taskDate = this.taskForm.taskDate;
          } else {
            // 定时任务
            taskData.repeatType = this.taskForm.repeatType;
            taskData.validStartDate = this.taskForm.validDateRange[0];
            taskData.validEndDate = this.taskForm.validDateRange[1];
            
            if (this.taskForm.repeatType === 2) {
              taskData.weekDays = this.taskForm.weekDays;
            } else if (this.taskForm.repeatType === 3) {
              taskData.monthDays = this.taskForm.monthDays;
            }
          }

          this.submitting = true;
          this.$axios
            .post("api/patrol-server/patrolTask/add", taskData)
            .then(response => {
              if (response.data && response.data.code === 200) {
                this.$message.success("添加巡更任务成功");
                this.$router.push("/patrolTaskDisplay");
              } else {
                this.$message.error(response.data.message || "添加巡更任务失败");
              }
            })
            .catch(error => {
              console.error("添加巡更任务错误:", error);
              this.$message.error("添加巡更任务错误");
            })
            .finally(() => {
              this.submitting = false;
            });
        } else {
          return false;
        }
      });
    },

    // 取消
    cancel() {
      this.$router.push("/patrolTaskDisplay");
    }
  },
  
  watch: {
    'taskForm.communityId': function(val) {
      this.handleCommunityChange(val);
    },
    'taskForm.repeatType': function(val) {
      // 重置周和月的选择
      if (val === 1) {
        this.taskForm.weekDays = [];
        this.taskForm.monthDays = [];
      } else if (val === 2) {
        this.taskForm.monthDays = [];
        if (this.taskForm.weekDays.length === 0) {
          // 默认选择工作日
          this.taskForm.weekDays = [1, 2, 3, 4, 5];
        }
      } else if (val === 3) {
        this.taskForm.weekDays = [];
        if (this.taskForm.monthDays.length === 0) {
          // 默认选择1号
          this.taskForm.monthDays = [1];
        }
      }
    }
  }
}
</script>

<style scoped>
.patrol-task-add-container {
  padding: 20px;
}

.box-card {
  width: 100%;
  margin-bottom: 20px;
  box-shadow: 0 4px 18px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  transition: all 0.3s ease;
}

.box-card:hover {
  box-shadow: 0 6px 24px 0 rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
}

.header-title {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  display: flex;
  align-items: center;
}

.header-icon {
  margin-right: 8px;
  color: #409EFF;
  font-size: 22px;
}

.divider-content {
  font-size: 16px;
  font-weight: 500;
  color: #409EFF;
  display: flex;
  align-items: center;
}

.divider-content i {
  margin-right: 8px;
  font-size: 18px;
}

.point-list {
  margin-top: 10px;
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.point-list:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

.table-toolbar {
  padding: 12px 15px;
  background-color: #f5f7fa;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
}

.point-count {
  font-size: 14px;
  color: #606266;
  display: flex;
  align-items: center;
}

.point-count i {
  margin-right: 5px;
  color: #409EFF;
}

.el-form-item {
  margin-bottom: 25px;
  transition: all 0.3s ease;
}

.form-buttons {
  margin-top: 40px;
  text-align: center;
}

.form-buttons .el-button {
  padding: 12px 30px;
  font-size: 14px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.submit-button {
  padding: 12px 35px !important;
  font-size: 15px !important;
}

.submit-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}

.month-days-container {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 15px;
  background-color: #fafafa;
}

.month-day-checkbox {
  margin-right: 15px;
  margin-bottom: 10px;
  transition: all 0.2s ease;
}

.month-day-checkbox:hover {
  color: #409EFF;
}

.el-divider {
  margin: 30px 0;
}

.el-radio-group {
  margin-bottom: 10px;
  display: flex;
  flex-wrap: wrap;
}

.custom-radio-group {
  display: flex;
  gap: 20px;
}

.radio-content {
  padding: 10px 0;
}

.radio-description {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  margin-left: 20px;
}

.repeat-type-group {
  display: flex;
  gap: 30px;
}

.repeat-type-item {
  display: flex;
  align-items: center;
  padding: 5px 0;
}

.repeat-type-item i {
  margin-right: 5px;
}

.week-days-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 10px;
  background-color: #fafafa;
  border-radius: 8px;
  border: 1px solid #dcdfe6;
}

.day-checkbox {
  min-width: 80px;
  margin-right: 0 !important;
}

.time-picker-container {
  display: flex;
  align-items: center;
  gap: 5px;
}

.time-picker {
  width: 49%;
}

.time-separator {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 14px;
  width: 20px;
  flex-shrink: 0;
}

.task-config-section {
  background-color: #fafafa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
}

/* Animations */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
}

.animated-form .fade-in-item {
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.custom-table {
  border-radius: 4px;
  overflow: hidden;
}

/* Ensure element-ui components get proper styling */
:deep(.el-select),
:deep(.el-date-editor),
:deep(.el-input) {
  width: 100%;
}
</style>